﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 组件CRM创建WMS物流发运单明细
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMtoWMSAddSalesInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;


        public CRMtoWMSAddSalesInfoController(ILogger<TMStoWMSAddSalesInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            _logger = loggerFactory.CreateLogger<CRMtoWMSAddSalesInfoController>();
        }

        /// <summary>
        /// 组件CRM创建WMS物流发运单明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostCRMtoWMS([FromBody] TMStoWMSAddSalesInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMStoWMSAddSalesInfoResponseDto re = new TMStoWMSAddSalesInfoResponseDto();
            string waybill_no = strparm.waybill_no;
            string in_con = "";//目标WMS数据库
            try
            {
                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "factory_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_yb;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {
                    if (strparm.factory_code.Contains("gz"))
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                        DataTable so_dt = MethodHelp.GetTableInfo("TMS0125", dic, con);//获取物流计划明细，订单数据源
                        if (so_dt.Rows.Count>0)
                        {
                            WMS_SalesOrderCreateRequestDto data = new WMS_SalesOrderCreateRequestDto();
                            WMS_SalesOrderCreateHeaderDto header = new WMS_SalesOrderCreateHeaderDto();
                            List<WMS_SalesOrderCreateHeader> header_input = new List<WMS_SalesOrderCreateHeader>();
                            foreach (DataRow item in so_dt.Rows)
                            {
                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("waybill_no", waybill_no);//查询对应物流计划
                                dic.Add("saleorder_no", item["xsddh"].ToString());//查询对应物流计划
                                DataTable sod_dt = MethodHelp.GetTableInfo("TMS0126", dic, con);//获取物流计划明细，订单数据源
                                if (sod_dt.Rows.Count>0)
                                {
                                    List<WMS_SalesOrderCreate_Details> details_input = new List<WMS_SalesOrderCreate_Details>();
                                    //循环插入明细
                                    foreach (DataRow row in sod_dt.Rows)
                                    {
                                        details_input.Add(new WMS_SalesOrderCreate_Details
                                        {
                                            orderLineNo = DB.ToInt(row["xsddhh"].ToString()),
                                            sku = row["wlbm"].ToString(),
                                            qtyOrdered = DB.ToInt(row["sl"].ToString()),
                                            dedi03= row["xsddhh"].ToString(),
                                            dedi05 = row["xsddhh"].ToString(),
                                            dedi06 = row["fhmxhh"].ToString()
                                        }) ;
                                    }

                                    //添加到header
                                    if (details_input!=null)
                                    {
                                        header_input.Add(new WMS_SalesOrderCreateHeader
                                        {
                                            warehouseId = "H01",
                                            customerId = "H01",
                                            orderType = "GLJY",
                                            soReference1 = item["xsddh"].ToString(),
                                            soReference2 = item["xsddh"].ToString(),
                                            soReference3 = item["djh"].ToString(),
                                            consigneeId = item["khbm"].ToString(),
                                            consigneeName = item["khmc"].ToString(),
                                            hedi04 = "H01",
                                            hedi05 = "APPROVE",
                                            details = details_input
                                        }) ;
                                    }

                                   
                                }
                                else
                                {
                                    strMsg = "logistics_plan_no=<" + waybill_no + "> ,订单号=<"+ item["salesorderno"].ToString() + ">找不到对应明细信息!";
                                }
                                                            
                            }

                            if (header_input!=null)
                            {
                                header.header = header_input;
                            }
                            if (header!=null)
                            {
                                data.data = header;
                            }


                            if (data!=null)
                            {
                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "内部:组件WMS_销售订单新增");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                if (url_dt.Rows.Count > 0)
                                {
                                    string jsonText = JsonConvert.SerializeObject(data);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    WMS_SalesOrderCreateResponseDto psp = JsonConvert.DeserializeObject<WMS_SalesOrderCreateResponseDto>(reAgv);
                                    if (psp.code > 0)
                                    {
                                        strMsg = strMsg + "-" + "CRM ERR:" + psp.message;
                                    }
                                }                                
                            }



                        }
                        else
                        {
                            strMsg = "logistics_plan_no=<" + waybill_no + "> 找不到对应订单信息!";
                        }
                    }                                                       
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
